﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ECare.BUS;
using ECare.BUS.Data;
using ECare.Client.frms;

namespace ECare.Win.controls
{
    public partial class ucResources : DevExpress.XtraEditors.XtraUserControl
    {
        public ucResources()
        {
            InitializeComponent();

            this.Load += ucResources_Load;

            this.windowsUIButtonPanel1.ButtonClick += windowsUIButtonPanel1_ButtonClick;

            this.grd.CellDoubleClick += grd_CellDoubleClick;
        }

        void grd_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {if (e.RowIndex == -1)
                return;
            var entitye = this.grd.Rows[e.RowIndex].DataBoundItem as ResoucesInfo;
            var frm = new frmResourcesInfo {entity = entitye};
            frm.Saved += frm_Saved;
            frm.ShowDialog();
        }

        void windowsUIButtonPanel1_ButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {

            if (e.Button.Properties.Caption == "Edit"){
                if (this.grd.SelectedRows.Count == 0)
                    return;

                var entitye = this.grd.SelectedRows[0].DataBoundItem as ResoucesInfo;
                var frm = new frmResourcesInfo();
                frm.entity = entitye;
                frm.Saved += frm_Saved;
                frm.ShowDialog();

            }
            else if (e.Button.Properties.Caption == "New")
            {
                var frm = new frmResourcesInfo();
                frm.entity = null;
                frm.Saved += frm_Saved;
                frm.ShowDialog();
            }
            else
            {
                
            }
        }
        void frm_Saved(object entity)
        {
            if (source == null)
                source = new BindingList<ResoucesInfo>();
            var role = entity as ResoucesInfo;
            var findresult = source.FirstOrDefault(a => a.ResourceId == role.ResourceId);
            if (findresult == null)
                this.source.Add(role);

        }


        public BindingList<ResoucesInfo> source { get; set; }
        
        void ucResources_Load(object sender, EventArgs e)
        {
            this.source = new BindingList<ResoucesInfo>(ResourcesHelper.GetAllResources());
            this.grd.DataSource = this.source;}
    }
}
